<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class OperateLogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        $requestMethod = $request->getMethod();
        $allowedMethod = ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE'];
        if (in_array($requestMethod, $allowedMethod)) {

            $table = sprintf("operate_logs_%s", date("Ymd"));
            createOperateLogTable($table);

            DB::table($table)->insert([
                'method' => $request->getMethod(),
                'path' => $request->path(),
                'client_ip' => $request->getClientIp(),
                'request_data' => toJson($request->all()),
                'response_data' => $response->getContent(),
            ]);
            // dispatch(new OperateLogJob($data))->delay($now->addMinutes($delay));
        }

        return $response;
    }
}
